//
//  CompanyViewController.m
//  HuaRun
//
//  Created by admin on 17/8/28.
//  Copyright © 2017年 Sunny. All rights reserved.
//

#import "CompanyViewController.h"
#import "CompanyCell.h"
#import "Company_DetailViewController2.h"
#import "CompanyModel.h"
#import "Home_Search_NoteCell.h"
#import "MJRefreshGifHeader.h"
#import "MJRefreshGifHeader+CuRefreshHeader.h"

@interface CompanyViewController ()

@end

@implementation CompanyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    if (self.companyType == CompanyTypeMother) {
        self.navigationItem.title = NSLocalizedString(@"chooseCompany", nil);
        [self.tableView registerClass:[Home_Search_NoteCell class] forCellReuseIdentifier:@"UITableViewCell"];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }else {
        self.navigationItem.title = NSLocalizedString(@"company_list", nil);
        self.searchView.placeholderStr = NSLocalizedString(@"搜索公司名称", nil);
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

        [self.tableView registerClass:[CompanyCell class]
               forCellReuseIdentifier:@"CompanyCell"];
    }
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.companyType == CompanyTypeMother) {
        Home_Search_NoteCell * cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
        CompanyModel * companyModel = self.dataArray[indexPath.row];
        cell.valueLab1.text = [NSString stringWithFormat:@"%@", companyModel.name];
        
        return cell;
    }
    CompanyCell * cell = [tableView dequeueReusableCellWithIdentifier:@"CompanyCell" forIndexPath:indexPath];
    cell.companyModel = self.dataArray[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (self.companyType == CompanyTypeMother) {
//        return 44;
//    }
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (self.companyType == CompanyTypeMother) {
        CompanyModel * companyModel = self.dataArray[indexPath.row];
        self.clickBlock ? self.clickBlock(companyModel) : nil;
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    
    Company_DetailViewController2 * detailVC = [Company_DetailViewController2 new];
    CompanyModel * companyModel = self.dataArray[indexPath.row];
    detailVC.accountId = companyModel.id;
    detailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - method 
- (void)viewInit {
    [super viewInit];
}

- (void)dataInit {
    [super dataInit];

    [self loadData];
}

- (void)layoutInit {
    
    weakself(ws);
    [self.searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(ws.view).offset(kMargin10);
        make.right.mas_equalTo(ws.view).offset(-kMargin10);
        make.top.mas_equalTo(ws.view).offset(0);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(ws.view);
        make.bottom.mas_equalTo(ws.view).offset(-48);
        make.top.mas_equalTo(ws.searchView.mas_bottom).offset(0);
    }];

}
-(void)methodBind {
    
    weakself(ws);
    
    [self.tableView headerRefresh:^{
        [ws refreshData];
    }];
    
    self.searchView.clickBlock = ^(id result) {
        [ws searchBtnMethod];
    };
    [self.searchView.textField addTarget:self action:@selector(recoverOriginDataMethod:)
                        forControlEvents:(UIControlEventEditingChanged)];
    self.normalDZNEmptyDataSouce.reloadBlock = ^{
        [ws refreshData];
    };

}

    
- (void)recoverOriginDataMethod:(UITextField *)textField {
    if (textField.text.length == 0) {
        NSLog(@"恢复最初数据");
        [self loadData];
    }else {
        NSLog(@"准备搜索");
    }
}
    
- (void)loadData {
    
//    公司参数：orderBy，取值：name create modify，默认为name
    NSString * keyword = [NSString isemptyStr:self.searchView.textField.text] ? @"" : self.searchView.textField.text;
    
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl, kAccountListUrl];
    NSDictionary * dic = @{@"current": @(self.current),
                           @"size": @(self.size),
                           @"keyword": keyword,
                           @"isCRC": @"ALL",
                           @"orderBy": @"name"
                           };
    weakself(ws);
    
    [self showActivity:kLodingStr];

    [NetWorkHelper getWithURLString:url parameters:dic success:^(id object) {
        [ws hideAllAlert];

        [ws.tableView endHeaderRefresh];
        
        if (![object[@"code"] isEqual: kSuccessCode]) {
            [ws showWithText:[NSString showStringWithStr:object[@"msg"]]];
            return;
        }
        NSArray * array = [NSArray yy_modelArrayWithClass:[CompanyModel class] json:object[@"list"]];

        ws.dataArray = ws.current == 1 ? array : [ws.dataArray arrayByAddingObjectsFromArray:array];
        [ws.tableView reloadData];
        
        if (array.count >= ws.size) {
            [ws.tableView footerRefresh:^{
                [ws loadMoreData];
            }];
        }else {
            [ws.tableView hiddenFooter];
        }

    } failure:^(NSError *error) {
        [ws hideAllAlert];
        
//        NSLog(@"fail %@", error);
        [ws.tableView endHeaderRefresh];
        [ws showWithText:kNetworkError];
        [ws.normalDZNEmptyDataSouce setDznEmptyStatus:(DZNEmptyStatusFailure)];
    }];

}

- (void)refreshData {
    self.current = 1;
    [self loadData];
}

- (void)loadMoreData {
    self.current++;
    [self loadData];
}

//点击搜索按钮时， 页数置1，
- (void)searchBtnMethod {
    self.current = 1;
    
    [self loadData];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
